package com.swiftops.common.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.util.List;
import java.util.UUID;

@Service
public class HostInfoService {

    @Autowired
    private final DiscoveryClient discoveryClient;

    @Value("${spring.application.name}")
    private String serviceId;

    public static final String instanceId = UUID.randomUUID().toString().toUpperCase();

    public HostInfoService(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    public String getCurrentHostIp() {

        // 从注册中心获取当前主机信息
        List<ServiceInstance> instanceList = discoveryClient.getInstances(serviceId);

        String hostIp = null;

        for (ServiceInstance instance : instanceList) {
            String uuid = instance.getMetadata().get("instanceId");
            if (instanceId.equals(uuid)) {
                String host = instance.getHost();
                URI uri = instance.getUri();
                System.out.println(host);
                System.out.println(uri);
                hostIp = host;
            }
        }
        return hostIp;
    }
}
